package commons.base.http.example;

import javax.servlet.annotation.WebServlet;

import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest;
import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse;
import org.eclipse.jetty.websocket.servlet.WebSocketCreator;
import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;

@WebServlet("/websocket")
public class DefaultWebSocketServlet extends WebSocketServlet {

	private static final long serialVersionUID = 1L;

	@Override
	public void configure(WebSocketServletFactory factory) {
		factory.getPolicy().setIdleTimeout(30000);
		factory.setCreator(new DefaultCreator());
	}

}

class DefaultCreator implements WebSocketCreator {

	private DefaultWebSocket webSocket = new DefaultWebSocket();

	public DefaultCreator() {

	}

	@Override
	public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
		for (String subprotocol : req.getSubProtocols()) {
			if ("binary".equals(subprotocol)) {
				resp.setAcceptedSubProtocol(subprotocol);
				return webSocket;
			}
			if ("text".equals(subprotocol)) {
				resp.setAcceptedSubProtocol(subprotocol);
				return webSocket;
			}
		}
		
		return webSocket;
	}
}